//the text to link code (uriaggressive) is from Kim A. Brandt. See http://userscripts.org/scripts/show/7122
 const uriaggressive = /[a-z][a-z0-9+-.]*:((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
 const uri = /((http)s?|(ftp)|(mailto)):((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
 
 const uri2_57 = /[a-z0-9+-.(@)?]*\b\.((name)|([A-za-z]){2,3})\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
 const uri2_56 = /[a-z0-9+-.(@)?]*\b\.(com|net|org|edu|uk|au)\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
 
 const uri2 = /[a-z0-9+-.(@)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;

 const illegal = /^(a|button|label|legend|option|script|select|style|textarea|title)$/i;
 
 var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
 var _alertTimeOut = 3000;
		  
//pref consts		
const SMACK_AUTOURL   = "extensions.swaksmack.autourl_boolpref1";  
const SMACK_EASYURL   = "extensions.swaksmack.easyurl_boolpref1";
const SMACK_MAXURL = "extensions.swaksmack.maxurl_boolpref1";
const SMACK_MAXLENGTH = "extensions.swaksmack.maxurllength_intpref";
const SMACK_TRUNCURL = "extensions.swaksmack.truncurl_stringpref";
const SMACK_OUTWITALERT = "extensions.swaksmack.outwitwarn_boolpref1";
const SMACK_OUTWITVOTEALERT = "extensions.swaksmack.outwitvotewarn_boolpref1";
const SMACK_OUTWITRANDOM = "extensions.swaksmack.outwitrandom_boolpref1";
const SMACK_GURUGUESSALERT = "extensions.swaksmack.guruguesswarn_boolpref1";
const SMACK_POLLINTERVAL = "extensions.swaksmack.pollinterval_intpref";

const SMACK_ENABLEHL = "extensions.swaksmack.enablehl_boolpref1";
const SMACK_IGNORECASEHL = "extensions.swaksmack.ignorecasehl_boolpref1";
const SMACK_IGNORESPHL = "extensions.swaksmack.ignoreselfposts_boolpref1";
const SMACK_ENABLELRHL = "extensions.swaksmack.enableinlrhl_boolpref1";
const SMACK_KEYWORDHL1 = "extensions.swaksmack.keywordshl1_stringpref";
const SMACK_TCHL1 = "extensions.swaksmack.hltextcolor1_stringpref";
const SMACK_BTCHL1 = "extensions.swaksmack.hlbkcolor1_stringpref";
const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hlunderline1_boolpref1";
const SMACK_ITALICHL1 = "extensions.swaksmack.hlitalic1_boolpref1";
const SMACK_BOLDHL1 = "extensions.swaksmack.hlbold1_boolpref1";
const SMACK_WORDONLYHL1 = "extensions.swaksmack.wordonlyhl_boolpref1";
const SMACK_USERNAMEHL1 = "extensions.swaksmack.usernamehl1_stringpref";

//div ids used to find outwit opt in and answer elements
const SMACK_OUTWITCHATDIV = "chatPost";  // was "chat", commentInfo
const SMACK_COMMENTTEXT = "commentText";
const SMACK_COMMENTNICK = "chatNick";
const SMACK_COMMENTAVATAR = "chatAvatarContainer";
const SMACK_OUTWITCOMMENTDIV = "comment_comment";
const SMACK_PMDIV = "messagesContainer";
const SMACK_OUTWITCAPDIV = "captchaBox";
const SMACK_OUTWITANSWERDIV = "outwitAnswer";
const SMACK_OUTWITGURUGUESSDIV = "guruMakeGuess";
const SMACK_DEALDIV = "deal";
const SMACK_OUTWITCONDIV = "outwitContainer";
const SMACK_GURUCONDIV = "guruContainer";
//needed???
const SMACK_SHOWNAMEVALUE = "showName";
const SMACK_SHOWNAMEDIV = "The Daily Smack with Smack Daddy";

var chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link  { color: #FF7800 !important; } ";
var chatcsscommentTEMP = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link  { color: #FF7800 !important; } .commentText { background:#660a00; } ";
var chatupdate=1;
//REMOVWE var outwitAlertPref = true;
var outwitAlertAck = false;
var outwitVoteAck = false;
//REMOVE var outwitVoteAlertPref = true;

//REMOVE var guruguessAlertPref = true;
var guruguessAlertAck = false;
var _keywordDisplayLength = 15;

var _regExChatDiv = buildClassNameRegex(SMACK_OUTWITCHATDIV);

var _doc;

var _dealDivIntervalId;

//array to hold the chat div ids
var _chatIdArray = new Array();
//var _tabcontainer = gBrowser.tabContainer;

var _dynamicKeywords = new Array();

var _colorCommentMatchArray = new Array();

 function checkHost(doc) {
 	 	host = doc.location.host;
 	 	if (host == 'www.jellyfish.com' || host == 'jellyfish.com')
 	 		return true;
 	 	return false;	
 }
 
 function isPMArea(doc) {

 	if (doc == null) doc=content.document;
 	var hostPath = doc.location.pathname;
 	var matches = hostPath.match("/shoppers/me/messages");
 	if (matches != null) {
 		return true;
	}
	return false;
 }
 
  function isSmackShopArea(doc) {
  	if (doc == null) doc = content.document;
 	var hostPath = doc.location.pathname;
 	var matches = hostPath.match("/smacktv/channel");
 	if (matches != null) {
 		return true;
	}
	return false;
 }
 
  function isLRArea(doc) {
  	if (doc == null) doc = content.document;
  	var lrDiv = doc.getElementById('livingRoomName');
 		if (lrDiv != null) return true;
	return false;
 }
 
 function chatLinkColor(doc) {
 	if (doc == null) doc = content.document;
 				var heads = doc.getElementsByTagName("head");
			if (heads.length > 0) {
				var node = doc.createElement("style");
				node.innerHTML = chatcss;
				node.type = "text/css";
				heads[0].appendChild(node); 
			}
 }
 //from http://robertnyman.com/js/getElementsByClassName.js
function getElementsByClassName_ORG(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

function _getElementsByXPath(expression,parent) {
    var results = [];
    var query = document.evaluate(expression, parent || window.content.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
        results.push(query.snapshotItem(i));
    return results;
};
function getElementsByClassName(className,parent) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return _getElementsByXPath(q,parent);
}

function buildClassNameRegex(strClassName) {
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	return oRegExp;
}

function getElementsByClassName_OLD(oElm, strTagName, oRegExp){
	if (oRegExp == null) return;
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	//strClassName = strClassName.replace(/\-/g, "\\-");
	//var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

 function buildSearchString(searchArray) {
 	var searchreg = null;
 	if (searchArray == null) return searchreg;
	for (var i=0; i<searchArray.length;i++){
		if (searchArray[i] == null || searchArray[i]== "") continue;
		if (searchreg == null) {
			searchreg = searchArray[i].trim();
			continue;
		}
		searchreg = searchreg + '|' +  searchArray[i].trim(); 
	}
	return searchreg;
 }
 

 function commentColor(element, doc) {
 	///////////////////////
 
  if (isLRArea(doc) == true && getPreference(SMACK_ENABLELRHL) == false) {
 		//bool_highlight = false;
 		return;
 	}
 	var keywords = getPreference(SMACK_KEYWORDHL1);
	var usernames =getPreference(SMACK_USERNAMEHL1);
 	var chatRegExp = null;
  
 			//TODO --refactor this into something a bit cleaner
 			var searchFound = false;
 			if (keywords != null && keywords.length >0) {
 	 			keywords = keywords.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
 				keywords = buildSearchString(keywords);
 				searchFound = true;
 			}
 	 		if (_dynamicKeywords != null && _dynamicKeywords.length >0) {
 	 			var dwords = buildSearchString(_dynamicKeywords);
 	 			//alert('dwords pre cat ' + dwords);
 	 			if (keywords != null && keywords.length >0) keywords = keywords + '|' + dwords;
 	 			else keywords = dwords;
 	 			searchFound = true;
 	 		}
 			
 			//only build regex if we have something to build--otherwise things go very bad
			if (searchFound == true) {
				
				keywords = keywords.replace(/(\|$)|(,$)/g,'');

 				keywords = escapeRegExLiterals(keywords);

				if(getPreference(SMACK_IGNORECASEHL) == true) chatRegExp = new RegExp(keywords,"ig");  //was ig
				else chatRegExp = new RegExp(keywords,"g"); //was "g"
			}

 	
 	
 	///////////////////////
 	
		var commentPosts = getElementsByClassName("chatPost",element);
		var chatPost = commentPosts[0];
		if (chatPost == null) return;
		var commentTexts = getElementsByClassName(SMACK_COMMENTTEXT,chatPost);
		var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);  //"chatNick" "chatAvatarContainer"
		if (commentTexts == null || chatNick == null) return;
		var keywordMatch = false;
		var userNameMatch = false;
		var highlightKeywordsOnly = getPreference(SMACK_WORDONLYHL1);
		if (chatRegExp != null) {
			keywordMatch = colorByComment(commentTexts[0],chatRegExp, highlightKeywordsOnly);
		}

	
		if (usernames != null && usernames != "") {
			usernames = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
 			usernames = buildSearchString(usernames);
 			//ending with a | or , can be bad
 			usernames = usernames.replace(/(\|$)|(,$)/,'');
 			//alert(usernames);
			var usernameRegExp = new RegExp(usernames,"ig");
	  	userNameMatch = colorByUsername(chatNick[0],usernameRegExp);
		}
	

		

		if (keywordMatch == true && highlightKeywordsOnly == false) {
				var bkgrdColor = getPreference(SMACK_BTCHL1);
				chatPost.style.background='#'+ bkgrdColor;
				var textColor = getPreference(SMACK_TCHL1);
				chatPost.style.color='#'+ textColor;
				return;
		}
		
		//if matched on username, highlight entire post
		if (userNameMatch) {
			var bkgrdColor = getPreference(SMACK_BTCHL1);
			chatPost.style.background='#'+ bkgrdColor;
			var textColor = getPreference(SMACK_TCHL1);
			chatPost.style.color='#'+ textColor;
	
			//TEST
			//var chatAt = getElementsByClassName("chatAvatarContainer",chatPost);
			//var bkgrdColor = getPreference(SMACK_BTCHL1);
			//chatAt[0].style.border='5px solid #'+ bkgrdColor;
			
			//style.border='2px solid #ccc';
		}
}
 
 function colorByComment(element, oRegExp, highlightKeywords) {
 	if (element == null || oRegExp == null) return false;
 	if (highlightKeywords == null) highlightKeywords = false;
 	var underlineMatch = getPreference(SMACK_UNDERLINEHL1);
	var matches;
	var inputText = element.textContent;
	//var matchArray = new Array();		
	var matchFound = false;
 	//var matchArray = new Array();	
 		//fix href links and so that we don't try to color/underline--will break link			
 	var badToColor = element.getElementsByTagName("a");	

 					
	while ((matches = oRegExp.exec(inputText)) != null) {
		
		matchFound = true;
		if (underlineMatch == false && highlightKeywords == false) break;
		//temp fix for matches on the html links--for now don't attempt to color/underline
		if (badToColor != null && badToColor[0] !=null) break;
		//_end temp fix			
					
		var text = matches[0];
		var lastKWMatchIndex = _colorCommentMatchArray.indexOf(text);
		if (lastKWMatchIndex != -1) {
			continue;

		}

		 _colorCommentMatchArray.push(text);
		 var regextext = escapeRegExLiterals(text);
		 //var regextext = text.replace(_literals,"[$1]");
//			 alert(regextext);
		var mRegExp = new RegExp(regextext,"g");
		var newtext = text;
		if (underlineMatch == true) {
			newtext = '<u>'+text+'</u>';
		}
		if (highlightKeywords == true) {
			newtext = '<span style=\"color:#' + getPreference(SMACK_TCHL1) +';background:#' + getPreference(SMACK_BTCHL1) + '\">' + newtext + '</span>';	
		}
		//alert(element.innerHTML);
		element.innerHTML = element.innerHTML.replace(mRegExp, newtext);
		//for debug testing element.textContent = element.textContent.replace(mRegExp, newtext);
					
	}
	_colorCommentMatchArray = [];
	return matchFound;

 }
 
 function colorByUsername(element, oRegExp) {
 	if (element == null || oRegExp == null) return false;
 	var matchFound = false;
 	var matches = oRegExp.exec(element.textContent);
		if (matches != null) {
			matchFound = true;
			// draws box around username element.style.border='2px solid #ccc';
		}
		return matchFound;
 }
 
 function executePMLink(commentDiv, doc) {
 	if (doc == null) doc = content.document;
 	var chatDiv = doc.getElementById(commentDiv);
  var elements = doc.evaluate(".//text()", chatDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  if (elements == null) return;
  for (var i = 0; i < elements.snapshotLength; i++) textToLink(elements.snapshotItem(i), doc);
 }
 
 function execute(commentDiv, bool_highlight, doc)
 {
  if (doc == null) return;
 	if (bool_highlight == null) bool_highlight = true;
 
 var elements = doc.evaluate(".//text()", commentDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
 for (var ii = 0; ii < elements.snapshotLength; ii++) textToLink(elements.snapshotItem(ii), doc);

		if (getPreference(bool_highlight == true && SMACK_ENABLEHL) == true) {
			commentColor(commentDiv,doc);
	}
		



 }

 function textToLink(element, doc)
 {
     if (element.parentNode.tagName.match(illegal)) return;
     var generousMatch = getPreference(SMACK_EASYURL);
     var matches = element.nodeValue.match(uri);
     if (matches != null) {
	     var text = matches[0];
	     var index = element.nodeValue.indexOf(text);
	     if (index == 0)
	     {
	         if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc);
	         var link = doc.createElement("a");
	         //TEST for fixing link ref that have puncuation on the end
	         var newurl = element.nodeValue.replace(/([\.!,;:\*]*)$/i,'');
	         link.href = newurl;
	         //_TEST
	         ///073107 link.href = element.nodeValue;
	         link.rel="external";
	         element.parentNode.insertBefore(link, element);
	         link.appendChild(element); // TEXT TO LINK
	         slimFastUrl(element); 
		     }
		     else textToLink(element.splitText(index), doc);
  	 }
  	 else if (generousMatch == true){
  	 	matches = element.nodeValue.match(uri2);
  	 	if (matches != null) {
	     var text = matches[0];
	     var emailFound = false;
	     if (text.indexOf("@") != -1) emailFound = true;
	     var index = element.nodeValue.indexOf(text);
	     if (index == 0)
	     {
	         if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc);
	         var link = doc.createElement("a");
	         link.href = 'http://'+element.nodeValue;
	         if (emailFound == true) {
	         	link.href = 'mailto:'+element.nodeValue;
	         }
	         link.rel="external";
	         element.parentNode.insertBefore(link, element);
	         link.appendChild(element); // TEXT TO LINK    
	         slimFastUrl(element);       	
		     }
		     else textToLink(element.splitText(index), doc);
  	 }
  	 }

 }
 
 function slimFastUrl(element){
 	  if(element == null) return;
 	  var trimUrlLength = getPreference(SMACK_MAXURL);
 	  if (trimUrlLength == false) return;
 	  var maxUrlLength = getPreference(SMACK_MAXLENGTH);
 	  if (maxUrlLength <=0) {
 	  	var jellyfishstrings = document.getElementById("swaksmack-strings");
 	  	var error = jellyfishstrings.getString("maxUrlLengthError1");	
 	  	alert(error);
 	  	//var defPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService.getDefaultBranch());
 	  	var defPrefs = prefs.getDefaultBranch('extensions.swaksmack.');
			maxUrlLength = defPrefs.getIntPref('maxurllength_intpref');
			prefs.setIntPref(SMACK_MAXLENGTH, maxUrlLength);
 	  }
 	  var clippedUrlEnd=getPreference(SMACK_TRUNCURL);
 	  if (maxUrlLength > 0 && element.nodeValue.length > maxUrlLength){
	 		var replacelength = element.nodeValue.length;
	 		var l1 = clippedUrlEnd.length;
	 		if (l1 == maxUrlLength) l1=0;
			var front = element.substringData(0, maxUrlLength-l1);
			front = front+clippedUrlEnd;
			var tn = document.createTextNode(front);				 
			element.parentNode.replaceChild(tn,element.parentNode.firstChild);
	}
 }
 
 function externalLinks(doc) {
 	if (doc == null) doc = content.document;
 if (!doc.getElementsByTagName) return;
 var anchors = doc.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}

function commentSpellCheck(doc) {
	if (doc == null) doc = content.document;
	var commentdiv = doc.getElementById(SMACK_OUTWITCOMMENTDIV);
	if (commentdiv != null) {
		commentdiv.spellcheck = true;
	}
}


var _checkGuruGuess = false;

function registerChatListeners(doc) {
		var chatDiv = doc.getElementById('chat');

		if (chatDiv != null){
			chatDiv.addEventListener('DOMAttrModified', function(event) {
				//need to to proces the last added chat comment
				while (_chatIdArray.length >0) {
					execute(_chatIdArray.pop(), true, doc);
					externalLinks(doc);
					}
			}, true);
			
			chatDiv.addEventListener('DOMNodeInserted', function(event) {
						
				while (_chatIdArray.length >0) {execute(_chatIdArray.pop(), true, doc);}
				_chatIdArray.push(event.target);
				if (outwitAlertAck == false || outwitVoteAck == false) {
					var timer=doc.getElementById('liveObjectTimer');
					
					if (timer != null) {
						//alert('checking for contest');
						setTimeout("smackPoll()",_alertTimeOut);
					}
					if (_checkGuruGuess == true) {
						setTimeout("checkGuruGuess()",_alertTimeOut,doc);
						
					}
			}
			}, true);
			
	//		chatDiv.addEventListener('click', function(event) {
			//	alert(document.defaultView.liveObject);
	//		alert(window["liveObject"].duration);
	//			}, true);
	}
	
	var guru=doc.getElementById('guruContainer');
			if (guru != null){
				//alert('guru not null');
			guru.addEventListener('DOMAttrModified', function(event) {
				var guruguessAlertPref = getPreference(SMACK_GURUGUESSALERT);
				if (guruguessAlertPref == true) {
					if (guru.style.display == "block") {
					_checkGuruGuess = true;
				}
				else if (guru.style.display == "none") {
					//alert('guruguess display is none');
					_checkGuruGuess = false;
				}
			}
			}, true);
			
	}
	else {
		//alert('guru is null');
		_checkGuruGuess = false;
	}
	

	
}

function checkGuruGuess(doc) {
	if (doc == null) doc = content.document;
			
		if (guruguessAlertAck == false && doc.getElementById(SMACK_OUTWITGURUGUESSDIV) != null) {
			guruguessAlertAck = true;
			var jellyfishstrings = document.getElementById("swaksmack-strings");
	 	  var alert3 = jellyfishstrings.getString("guruguessWarn1");	
	 	  alert(alert3);
		}
		else if (doc.getElementById(SMACK_OUTWITGURUGUESSDIV) == null) {
			guruguessAlertAck = false;
		}

}





function smackPoll() {
	var outwitAlertPref = true;
	var outwitVoteAlertPref = true;
	var guruguessAlertPref = true;
	try {
			 		outwitAlertPref = getPreference(SMACK_OUTWITALERT);
			 		outwitVoteAlertPref = getPreference(SMACK_OUTWITVOTEALERT);
			 		guruguessAlertPref = getPreference(SMACK_GURUGUESSALERT);
	}
	catch(Excepion){}
	
	if (outwitAlertPref == true) {
		if(outwitAlertAck == false && _doc.getElementById(SMACK_OUTWITCAPDIV) != null){
			outwitAlertAck = true;
			outwitVoteAck = false;
			var jellyfishstrings = document.getElementById("swaksmack-strings");			var alert1 = jellyfishstrings.getString("outwitWarn1");
			alert(alert1);
		} 
		
		if (outwitVoteAck == false && _doc.getElementById(SMACK_OUTWITANSWERDIV)) {
			outwitAlertAck = false;
			outwitVoteAck = true;
			if (outwitVoteAlertPref == true) {
				var randomGuess = Math.ceil(Math.random()*6);				
				var jellyfishstrings = document.getElementById("swaksmack-strings");
			 	var alert2 = jellyfishstrings.getString("outwitVoteWarn1");
			 	var outwitRandomPref = true;
			 	try {
			 		outwitRandomPref = getPreference(SMACK_OUTWITRANDOM);	
				}
				catch(Excepion){}
				if (outwitRandomPref){
					alert2 += "\n" + jellyfishstrings.getString("outwitRandom1") + randomGuess;
				}
				alert(alert2);
			}
		} 
	}
	if (guruguessAlertPref == true){
		if(guruguessAlertAck == false && _doc.getElementById(SMACK_OUTWITGURUGUESSDIV) != null){
			_checkGuruGuess = false;
			guruguessAlertAck = true;
			var jellyfishstrings = document.getElementById("swaksmack-strings");
			var alert3 = jellyfishstrings.getString("guruguessWarn1");	
			alert(alert3);
		} else if (_doc.getElementById(SMACK_OUTWITGURUGUESSDIV) == null) {
			guruguessAlertAck = false;
		}
	}
}

// swaksmack context menu stuff

function swakContextVisibilityOn() {
var menuitem = document.getElementById("swaksmack-context-menu");
menuitem.setAttribute("hidden","false");
menuitem = document.getElementById("contextmenu-addkeywords");
menuitem.setAttribute("hidden","false");
menuitem = document.getElementById("contextmenu-listkeywords");
menuitem.setAttribute("hidden","false");
menuitem = document.getElementById("contextmenu-clearkeywords");
menuitem.setAttribute("hidden","false");
}

function swakContextShowing() {
	//alert('contextShowing');
  var menuitem = document.getElementById("contextmenu-addkeywords");
  if (gContextMenu.isTextSelected) {
      var keyword;
	  if (gContextMenu.searchSelected)
			keyword = gContextMenu.searchSelected();
		else
			keyword = getBrowserSelection();
      if (keyword.length > _keywordDisplayLength) 
		keyword = keyword.substr(0,_keywordDisplayLength-1) + "...";
      var displaytext = "Add \"" + keyword + "\" to SwakSmack highlights.";
      menuitem.setAttribute("label", displaytext);
      menuitem.setAttribute("hidden","false");
  }
  else {
  	menuitem.setAttribute("hidden","true");
  }
}

function chatAddKeywords() {
	//alert('Do keyword stuff');
		var keyword = "";
	if (gContextMenu.onTextInput) 
	{
		alert('Do keyword stuff on textinput');
		keyword = document.popupNode;
		keyword = keyword.value.substring(keyword.selectionStart, keyword.selectionEnd);
		if (keyword.length>_keywordDisplayLength) 
			keyword = keyword.substr(0,_keywordDisplayLength-1);
	}
		else 
	{
		if (gContextMenu.searchSelected)
			keyword = gContextMenu.searchSelected();
		else
			keyword = getBrowserSelection();
		if (keyword.length == 0)
		{
			//do nothing? /?an alert?
			return;
		}
	}
	if (keyword.length>0)
	{
		//keyword = keyword.replace(' ,',',').replace(', ',',').replace(' ','\s').split(','); // Allow for spaces in usernames
		//alert(keyword);
		_dynamicKeywords.push(keyword);
	}

	}
	
	function chatClearKeywords(){
		//clear the dynamic keywords
		//keywords specified in options are kept
		_dynamicKeywords = [];
}

	function chatListKeywords(){
		//list keywords
		var words = getPreference(SMACK_KEYWORDHL1);
		var usernames = getPreference(SMACK_USERNAMEHL1);
		var list = 'SwakSmack Keywords\n';
		if (words != null && usernames != null) {
			list = list + '\nMain Keywords: \n';
			if (usernames != null) list = list + 'Usernames: ' + usernames +'\n';
			if (words != null) list = list + 'Keywords: ' + words +'\n';		
		}
		if (_dynamicKeywords !=null && _dynamicKeywords.length>0) {
			list = list + '\nDynamic Keywords: \n' +  _dynamicKeywords.toString();
		}
		
		alert(list);
}


var swaksmack = {
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("swaksmack-strings");
    document.getElementById("contentAreaContextMenu")
            .addEventListener("popupshowing", function(e) { this.showContextMenu(e); }, false);
    //add onload listener for web pages        
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent) {
      appcontent.addEventListener("load", this.onPageLoad, true);  
      appcontent.addEventListener("load", this.showContextMenu, true);        
    }

          
  },
  onPageLoad: function(aEvent) {
     var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
    // do something with the loaded page.
    // doc.location is a Location object (see below for a link).
    // You can use it to make your code executed on certain pages only.
    if (checkHost(doc) == true) {
    	//store doc ref for smack shopping document
    	if (isSmackShopArea(doc)) {
    		//alert('smack area found');
    	_doc = doc;
    	window._doc = doc;
    }
    	//check to see if in the private message area
    	if (isPMArea(doc) == true) {
    		executePMLink(SMACK_PMDIV, doc);
    		return;
    	}
    	commentSpellCheck(doc);
    	chatLinkColor(doc);
    	
    	//REMOVE outwitAlertPref = getPreference(SMACK_OUTWITALERT);
    	//REMOVE outwitVoteAlertPref = getPreference(SMACK_OUTWITVOTEALERT);
    	//REMOVE guruguessAlertPref = getPreference(SMACK_GURUGUESSALERT);

    	registerChatListeners(doc);
    	registerChatPostListener();
    	
    	//menu stuff
    	  
    	  var menu = document.getElementById("contentAreaContextMenu");
    	  //alert(menu);
  			menu.addEventListener("popupshowing", swakContextShowing, false);
  			swakContextVisibilityOn();
			
    }
  },

  showContextMenu: function(event) {
    // show or hide the menuitem based on what the context menu is on
    // see http://kb.mozillazine.org/Adding_items_to_menus
    //document.getElementById("context-jellyfish").hidden = gContextMenu.onImage;  //org
    document.getElementById("context-swaksmack").hidden = !checkHost();
  },
  onMenuItemCommand: function(e) {
  	
  	//no longer needed for chat/url processing --remove menu item???
  	//execute(SMACK_OUTWITCHATDIV);
  	//externalLinks();

                                
  },

};
window.addEventListener("load", function(e) { swaksmack.onLoad(e); }, false);

